<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-left">
        <div class="logo-container">
          <div class="logo-icon">
            <i class="el-icon-star-on" style="font-size: 80px;"></i>
          </div>
          <h1>宠物管理系统</h1>
          <p>专业的宠物服务平台</p>
        </div>
      </div>

      <div class="login-right">
        <h2>用户登录</h2>
        <el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="login-form" label-width="0">
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名（admin/user1）"
              prefix-icon="el-icon-user"
              clearable
              size="large"
              style="width: 100%;">
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码（默认：123456）"
              prefix-icon="el-icon-lock"
              show-password
              size="large"
              style="width: 100%;"
              @keyup.enter.native="handleLogin">
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
            <el-button type="text" style="float: right">忘记密码？</el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleLogin"
                       style="width: 100%" size="large">
              登录
            </el-button>
          </el-form-item>

          <el-form-item>
            <div class="register-link">
              还没有账号？
              <el-button type="text" @click="goToRegister">立即注册</el-button>
            </div>
          </el-form-item>
        </el-form>

        <div class="login-tips">
          <p style="color: #999; font-size: 12px; text-align: center; margin-top: 20px;">
            默认账号：admin（管理员）/ user1（普通用户）<br>
            默认密码：123456
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/auth'

export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        username: '',
        password: '',
        remember: false
      },
      defaultAccounts: {
        admin: { username: 'admin', password: '123456', role: 'admin' },
        user: { username: 'user1', password: '123456', role: 'user' }
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    handleLogin () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true

          // 调用登录API
          login({
            username: this.loginForm.username,
            password: this.loginForm.password
          }).then(response => {
            this.loading = false

            console.log('登录响应：', response)

            // 处理响应数据 - 支持多种响应格式
            let data = null
            let code = null
            let message = null

            // 格式1: { code: 200, data: {...}, message: '...' }
            if (response && response.code !== undefined) {
              code = response.code
              data = response.data
              message = response.message || response.msg
            }
            // 格式2: 直接返回数据对象
            else if (response && (response.token || response.username)) {
              code = 200
              data = response
            }
            // 格式3: 嵌套的data
            else if (response && response.data) {
              if (response.data.code !== undefined) {
                code = response.data.code
                data = response.data.data || response.data
                message = response.data.message || response.data.msg
              } else {
                code = 200
                data = response.data
              }
            }

            // 判断登录是否成功
            if (code === 200 && data) {
              // 提取用户信息
              const token = data.token || data.accessToken
              const username = data.username || this.loginForm.username
              // 处理 role，兼容多种数据格式
              let role = data.role || ''
              if (!role && data.authorities && Array.isArray(data.authorities) && data.authorities.length > 0) {
                role = data.authorities[0].authority || ''
              }
              const userType = data.userType !== undefined ? data.userType : (username === 'admin' ? 2 : 1)
              const userId = data.userId || data.id
              const realName = data.realName || data.name || ''
              const email = data.email || ''
              const phone = data.phone || ''

              // 保存token
              if (token) {
                localStorage.setItem('token', token)
              }

              // 保存用户信息
              const userInfo = {
                userId,
                username,
                realName,
                email,
                phone,
                role,
                userType
              }
              localStorage.setItem('userInfo', JSON.stringify(userInfo))

              // 根据用户类型跳转到不同页面
              const isAdmin = userType === 2 ||
                            role === 'ROLE_ADMIN' ||
                            role === 'admin' ||
                            username === 'admin' ||
                            username.toLowerCase() === 'admin'

              if (isAdmin) {
                this.$message.success({ message: '管理员登录成功！', duration: 800 })
                this.$router.push('/admin/dashboard')
              } else {
                this.$message.success({ message: '登录成功！', duration: 800 })
                this.$router.push('/user/home')
              }
            } else {
              // 登录失败
              const errorMsg = message || '登录失败，请检查用户名和密码'
              this.$message.error({ message: errorMsg, duration: 800 })
            }
          }).catch(error => {
            this.loading = false
            console.error('登录失败：', error)

            // 处理错误响应
            let errorMessage = '登录失败，请检查用户名和密码'

            if (error.response) {
              // 服务器返回了错误响应
              const data = error.response.data
              errorMessage = (data && (data.message || data.msg)) || errorMessage

              // 如果是401，说明用户名或密码错误
              if (error.response.status === 401) {
                errorMessage = '用户名或密码错误'
              }
            } else if (error.message) {
              // 网络错误或其他错误
              if (error.message.includes('Network') || error.message.includes('timeout') || error.message.includes('ECONNREFUSED')) {
                errorMessage = '网络连接失败，请检查后端服务是否启动（http://localhost:8080）'
              } else if (!error.message.includes('请求失败')) {
                errorMessage = error.message
              }
            }

            this.$message.error({ message: errorMessage, duration: 800 })
          })
        }
      })
    },
    goToRegister () {
      this.$router.push('/register')
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  display: flex;
  width: 900px;
  min-height: 500px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.logo-container {
  text-align: center;
}

.logo-icon {
  font-size: 80px;
  margin-bottom: 20px;
  animation: bounce 2s infinite;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-icon i {
  font-size: 80px;
  color: white;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.login-left h1 {
  font-size: 36px;
  margin: 0 0 15px 0;
}

.login-left p {
  font-size: 18px;
  margin: 0;
  opacity: 0.9;
}

.login-right {
  flex: 1;
  padding: 60px 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-right h2 {
  font-size: 28px;
  margin: 0 0 40px 0;
  color: #333;
  text-align: center;
}

.login-form {
  margin-bottom: 20px;
  width: 100%;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  width: 100%;
}

.register-link {
  text-align: center;
  color: #666;
}

.other-login {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style>
